package com.example.mqtt.service;

import com.example.mqtt.model.DataEntry;
import com.example.mqtt.repository.DataRepository;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class MqttConsumerService {

    private final IMqttClient mqttClient;
    private final DataRepository dataRepository;
    private final EmailService emailService;

    // 手动构造函数注入（解决Lombok与Qualifier的兼容问题）
    @Autowired
    public MqttConsumerService(
            @Qualifier("mqttConsumer") IMqttClient mqttConsumerClient,
            DataRepository dataRepository,
            EmailService emailService
    ) {
        this.mqttClient = mqttConsumerClient;
        this.dataRepository = dataRepository;
        this.emailService = emailService;
    }

    @PostConstruct
    public void subscribe() throws MqttException {
        System.out.println("开始订阅主题：sensor/topic");
        mqttClient.subscribe("sensor/topic", (topic, message) -> {
            JSONObject json = new JSONObject(new String(message.getPayload()));
            BigDecimal value = json.getBigDecimal("data");

            // 保存到数据库
            DataEntry entry = new DataEntry();
            entry.setDataValue(value);
            dataRepository.save(entry);

            // 触发阈值报警
            if (value.compareTo(new BigDecimal("0.90")) > 0) {
                emailService.sendAlertEmail(value);
                System.out.println("阈值报警：" + value);
            }
        });
    }
}
